<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin-bottom: 20px;">
      <el-button type="primary" size="medium"
                 @click="$router.push('/sys-admin/permission/role/add-new')">添加角色</el-button>
    </div>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="角色名称" width="100" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>

      <el-table-column label="配置管理员" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" @click="openEditAdminDialog(scope.row)">配置管理员</el-button>
        </template>
      </el-table-column>
      <el-table-column label="配置权限" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" @click="openEditPremissionDialog(scope.row)">配置权限</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-edit" circle type="primary"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="small" icon="el-icon-delete" circle type="danger"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px auto;text-align: right;">
      <el-pagination
          @current-change="changePageNum"
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage">
      </el-pagination>
    </div>

    <el-dialog title="配置管理员" :visible.sync="dialogAdminFormVisible"
               @closed="resetForm('editAdminForm')">
      <el-form :model="editAdminForm" ref="editAdminForm">
        <el-form-item>
          <p style="text-align: center; margin: 10px 20px;font-weight: bold; font-size: 22px">
            {{editAdminForm.roleName}}
          </p>
          <div style="text-align: center;">
            <el-transfer
                style="text-align: left; display: inline-block"
                v-model="editAdminForm.adminIds"
                :props="{key: 'id',label: 'nickname'}"
                :data="adminListOptions"
                @change="submitEditAdminForm"
                filterable
                :render-content="renderAdminFunc"
                :titles="['管理员列表', '已有管理员']"
                :button-texts="['移除管理员', '添加管理员']"
                :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}">
            </el-transfer>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAdminFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="配置权限" :visible.sync="dialogPermissionFormVisible"
               @closed="resetForm('editPermissionForm')">
      <el-form :model="editPermissionForm" ref="editPermissionForm">
        <el-form-item>
          <p style="text-align: center; margin: 10px 20px;font-weight: bold; font-size: 22px">
            {{editPermissionForm.roleName}}
          </p>
          <div style="text-align: center;">
            <el-transfer
                style="text-align: left; display: inline-block"
                v-model="editPermissionForm.permissionIds"
                :props="{key: 'id',label: 'nickname'}"
                :data="permissionListOptions"
                @change="submitEditPermissionForm"
                filterable
                :render-content="renderPermissionFunc"
                :titles="['权限列表', '已有权限']"
                :button-texts="['移除权限', '添加权限']"
                :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}">
            </el-transfer>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPermissionFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑角色" :visible.sync="dialogFormVisible"
               @closed="resetForm('editForm')">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="130px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import global from '../../../Global'
let preAdminUrl = global.preAdmins ;
let preRoleUrl = global.preRoles;
let prePermissionUrl = global.prePermissions;
let queryAll = global.queryAll ;
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,

      dialogFormVisible: false,
      editForm: {
        name: '',
        description: '',
        sort: ''
      },

      dialogAdminFormVisible: false,
      adminListOptions: [],
      editAdminForm: {
        roleId: '',
        roleName: '',
        adminIds: []
      },

      dialogPermissionFormVisible: false,
      permissionListOptions: [],
      editPermissionForm: {
        roleId: '',
        roleName: '',
        permissionIds: []
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序序号', trigger: 'blur' },
          { pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //el-transfer菜单项列表数据展示拼接
    renderAdminFunc(h, option) {
      return <span>{ option.id } - { option.nickname }</span>;
    },
    renderPermissionFunc(h, option) {
      return <span>{ option.id } - { option.name }</span>;
    },
    //管理员配置Dialog
    openEditAdminDialog(role){
      this.editAdminForm.roleId = role.id;
      this.editAdminForm.roleName = role.name;
      this.dialogAdminFormVisible = true;
      this.loadAllAdminList();
      this.loadAdminRoleList();
    },
    //管理员配置提交
    submitEditAdminForm(value, direction, movedKeys) {
      let urlMethod = '';
      if(direction == 'left'){
        urlMethod = 'deletesAdminRole';
      }else if(direction == 'right'){
        urlMethod = 'insertsAdminRole';
      }
      let url = preRoleUrl + "/" + this.editAdminForm.roleId + "/" + urlMethod
          +"?adminIds="+movedKeys;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '配置管理员成功！'
          });
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },

    //权限配置Dialog
    openEditPremissionDialog(role){
      this.editPermissionForm.roleId = role.id;
      this.editPermissionForm.roleName = role.name;
      this.dialogPermissionFormVisible = true;
      this.loadAllPermissionList();
      this.loadRolePermissionList();
    },
    //权限配置提交
    submitEditPermissionForm(value, direction, movedKeys) {
      let urlMethod = '';
      if(direction == 'left'){
        urlMethod = 'deletesRolePermission';
      }else if(direction == 'right'){
        urlMethod = 'insertsRolePermission';
      }
      let url = preRoleUrl + "/" + this.editPermissionForm.roleId + "/" + urlMethod
          +"?permissionIds="+movedKeys;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '配置权限成功！'
          });
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },

    //角色修改Dialog
    openEditDialog(role){
      let url = preRoleUrl + "/" + role.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        }
      });
    },
    //角色修改
    submitEditForm(){
      let url = preRoleUrl + "/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '编辑角色成功！'
          });
          this.dialogFormVisible = false;
          this.loadRoleList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadRoleList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //角色删除确认提示
    openDeleteConfirm(role) {
      this.$confirm('此操作将永久删除【 ' + role.id + '-' + role.name + ' 】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(role);
      }).catch(() => {
      });
    },
    //角色删除
    handleDelete(role){
      let url = preRoleUrl + "/" + role.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify.success({title: '成功',
            message: '删除成功'
          });

          this.loadRoleList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadRoleList();
            }
          });
        }else if(jsonResult.state == 40900){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });

    },
    //分页——翻页
    changePageNum(value){
      this.$router.replace("?pageNum="+value);
      this.loadRoleList();
    },
    //加载角色分页列表
    loadRoleList(){
      let pageNum = this.$router.currentRoute.query.pageNum;
      if(!pageNum){
        pageNum = 1;
      }
      let url = preRoleUrl+"?pageNum="+ pageNum;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }else if(jsonResult.state == 40100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              localStorage.removeItem("localJwt");
              this.$router.push("/login");
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //加载管理员全列表
    loadAllAdminList(){
      let url = preAdminUrl+queryAll;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.adminListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //获取角色ID下所有的管理员
    loadAdminRoleList(){
      let url = preRoleUrl + "/" +this.editAdminForm.roleId + "/admins";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editAdminForm.adminIds = jsonResult.data;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //加载权限全列表
    loadAllPermissionList(){
      let url = prePermissionUrl+queryAll;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.permissionListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //获取角色ID下所有的权限
    loadRolePermissionList(){
      let url = preRoleUrl + "/" +this.editPermissionForm.roleId + "/permissions";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editPermissionForm.permissionIds = jsonResult.data;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.adminListOptions = [];
      this.permissionListOptions = [];
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadRoleList();
  }
}
</script>
<style>
.el-transfer-panel{
  width:260px !important;
}
</style>